<template>
  <ElButton @click="saveData">保存数据</ElButton>
  <BaseAgGrid v-bind="gridOptions" />
</template>

<script setup lang="ts">
import BaseAgGrid from '@/components/BaseAgGrid.vue'
import { ref, shallowRef } from 'vue'
import { type GridApi, type GridOptions } from 'ag-grid-community'
import type { IOlympicData } from '@/views/types'

import json from './data/cus-cmp.json'
const gridApi = shallowRef<GridApi<IOlympicData> | null>(null);
const rowData = ref<Array<IOlympicData>>(json);
const gridOptions = ref<GridOptions<IOlympicData>>({
  rowData: rowData.value,
  enableCellSpan: true,
  columnDefs: [
    // 行 文字居中
    { field: 'name', cellStyle: { textAlign: 'center' } },
    { field: 'age' },
    { field: 'gender' },
    { field: 'phone' },
    { field: 'email' },
    { field: 'address' },
    { field: 'company' },
    { field: 'rate' },
  ],
  defaultColDef: {
    editable: true,
    flex: 1,
  },
  onGridReady: (event) => {
    // 表格初始化完成 未渲染
    console.log(`output-> api context type`, event.api, event.context, event.type)
    gridApi.value = event.api;
  },
  rowClassRules: {
    "ag-row-dirty": (params) => {
      return params.data?.isEdit ?? false;
    }
  },
  // 如果cell更改了则需要刷新一下表格
  onCellValueChanged: (event) => {
    console.log(`output->event changed`, event.node)
    // 如果没值(undefined null 0) 则跳过
    if (!event.oldValue && !event.newValue) return;
    // 如果值没有更新则跳过
    else if (event.oldValue == event.newValue) return;
    else {
      event.data.isEdit = true;
      // 重绘当前行样式
      event.api.redrawRows({ rowNodes: [event.node] });
      // 重绘单元格样式
      // event.api.refreshCells({ rowNodes: [event.node], columns: [event.column] });
    }
  }
})

// 刷新样式
// setData();
// function setData() {
//   gridApi.value!.forEachNode(function (rowNode) {
//     rowNode.setData(rowNode.data!);
//   });
// }

function saveData() {
  const data = gridOptions.value.rowData?.filter(m => m.isEdit ?? false);
  console.log(`output->data`, data)
}
</script>

<style>
.ag-row-dirty {
  background-color: #fff8e1 !important;
  /* 浅黄色 */
  /* 可选：加个边框或阴影 */
  /* box-shadow: inset 4px 0 #ffc107; */
}
</style>

<style scoped>
/* 自定义脏行样式, 其他项目中生效 在当前项目中没有生效 */
:deep(.ag-grid-vue) .ag-row-dirty {
  background-color: #fff8e1 !important;
  /* 浅黄色 */
  /* 可选：加个边框或阴影 */
  /* box-shadow: inset 4px 0 #ffc107; */
}
</style>
